package gorm

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
	"server/chat_room_server/internal/config"
	"server/chat_room_server/model/entity"
)

func NewDB(c config.Config) (db *gorm.DB) {
	// 暂时先使用这个数据库
	liteDB, err := NewSqlLiteDB(c)
	if err != nil {
		logx.Errorf(err.Error())
		panic(err)
	}
	return liteDB
	//return NewMysqlDB(c)
}

func initDB(db *gorm.DB) {
	// 自动迁移更新表结构
	db.AutoMigrate(&entity.User{}, &entity.Group{}, &entity.Users{}, &entity.UserGroup{})

	db.Unscoped().Where("deleted_at is null").Delete(&entity.User{})
	db.Unscoped().Where("deleted_at is null").Delete(&entity.Group{})
	db.Unscoped().Where("deleted_at is null").Delete(&entity.Users{})
	db.Unscoped().Where("deleted_at is null").Delete(&entity.UserGroup{})
	user1 := entity.User{
		UserId:   1,
		Name:     "zhangSan",
		Password: "2868463718",
	}
	user2 := entity.User{
		UserId:   2,
		Name:     "lisi",
		Password: "2868463718",
	}
	user3 := entity.User{
		UserId:   3,
		Name:     "wangwu",
		Password: "2868463718",
	}
	user4 := entity.User{
		UserId:   4,
		Name:     "zhaoliu",
		Password: "2868463718",
	}

	tx := db.Debug().Create(&user1)
	fmt.Println(tx)
	db.Debug().Create(&user2)
	db.Debug().Create(&user3)
	db.Debug().Create(&user4)

	group1 := entity.Group{
		GroupId:  1,
		Name:     "chat room ",
		NickName: "hahahaha",
	}
	db.Debug().Create(&group1)

	userGroup1 := entity.UserGroup{
		UserId:  user1.ID,
		GroupId: group1.ID,
	}
	userGroup2 := entity.UserGroup{
		UserId:  user2.ID,
		GroupId: group1.ID,
	}
	userGroup3 := entity.UserGroup{
		UserId:  user3.ID,
		GroupId: group1.ID,
	}
	db.Debug().Create(&userGroup1)
	db.Debug().Create(&userGroup2)
	db.Debug().Create(&userGroup3)

	users1 := entity.Users{
		UserId1: user1.ID,
		UserId2: user2.ID,
	}
	users2 := entity.Users{
		UserId1: user1.ID,
		UserId2: user3.ID,
	}
	users3 := entity.Users{
		UserId1: user1.ID,
		UserId2: user4.ID,
	}
	users4 := entity.Users{
		UserId2: user2.ID,
		UserId1: user3.ID,
	}
	users5 := entity.Users{
		UserId2: user2.ID,
		UserId1: user4.ID,
	}
	users6 := entity.Users{
		UserId2: user3.ID,
		UserId1: user4.ID,
	}
	db.Debug().Create(&users1)
	db.Debug().Create(&users2)
	db.Debug().Create(&users3)
	db.Debug().Create(&users4)
	db.Debug().Create(&users5)
	db.Debug().Create(&users6)

	var users []entity.User
	db.Debug().Find(&users)
	fmt.Println(users)
	var groups []entity.Group
	db.Debug().Find(&groups)
	fmt.Println(groups)
	var userss []entity.Users
	db.Debug().Find(&userss)
	fmt.Println(userss)
	var userGroups []entity.UserGroup
	db.Debug().Find(&userGroups)
	fmt.Println(userGroups)

}
